package com.bgamq.atcrowd.mvc.controller;

import com.bgamq.atcrowd.entity.Menu;
import com.bgamq.atcrowd.service.api.MenuService;
import com.bgamq.atcrowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author admin
 */
@RestController
public class MenuController {

    private final MenuService menuService;

    @Autowired
    public MenuController(MenuService menuService) {
        this.menuService = menuService;
    }



    @RequestMapping(value = "/menu/get/whole/tree.json", method = RequestMethod.POST)
    public ResultEntity<Menu> getWholeTreeNew() {
        List<Menu> menuList = menuService.getAll();
        Menu root = null;

        Map<Integer, Menu> menuMap = new HashMap<>();

        for (Menu menu : menuList) {
            Integer pid = menu.getId();
            menuMap.put(pid, menu);
        }

        for (Menu menu : menuList) {
            Integer pid = menu.getPid();
            if (pid == null) {
                root = menu;
                continue;
            }

            Menu father = menuMap.get(pid);

            father.getChildren().add(menu);

        }

        return ResultEntity.successWithData(root);
    }


    @RequestMapping(value = "menu/save.json", method = RequestMethod.POST)
    public ResultEntity<String> addMenu(Menu menu) {

        menuService.saveMenu(menu);

        return ResultEntity.successWithoutData();
    }


    @RequestMapping("/menu/update.json")
    public ResultEntity<String> updateMenu(Menu menu) {
        menuService.updateMenu(menu);
        return ResultEntity.successWithoutData();
    }


    @RequestMapping("/menu/remove.json")
    public ResultEntity<String> removeMenu(@RequestParam("id") Integer id) {
        menuService.removeMenu(id);
        return ResultEntity.successWithoutData();
    }


}
